<template>
    <!-- 搜索和查找 -->
    <div class="user-header">
        <el-button type="primary" @click="handleAdd">+新增</el-button>
        <el-form :model="formInline" :inline="true">
            <el-form-item>
                <el-input v-model="formInline.keyword" placeholder="请输入用户名" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
            </el-form-item>
        </el-form>
    </div>
    <!-- 表格 -->
    <div class="table">
        <el-table :data="list" height="530px">
            <el-table-column v-for="item in tableLabel" :key="item.prop" :label="item.label" :prop="item.prop"
                :width="item.width ? item.width : 160" />
            <el-table-column label="操作" min-width="180">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @current-change="changePage" layout="prev, pager, next" :total="config.total" />
    </div>
    <!-- 新增用户 -->
    <el-dialog v-model="dialogVisible" title="新增用户" width="40%" :before-close="handleClose">
        <el-form :inline="true" :model="formUser" ref="userForm">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="姓名" prop="name" :rules="[{ required: true, message: '姓名是必填项' }]">
                        <el-input v-model="formUser.name" placeholder="请输入姓名" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="年龄" prop="age" :rules="[{ required: true, message: '年龄是必填项' },
                    { type: 'number', message: '年龄必须是数字' },
                    ]">
                        <el-input type="text" autocomplete="off" v-model.number="formUser.age" placeholder="请输入年龄" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="性别" prop="sex" class="sex-select"
                        :rules="[{ required: true, message: '性别是必填项' }]">
                        <el-select v-model="formUser.sex" placeholder="请选择" clearable>
                            <el-option label="男" value="0" />
                            <el-option label="女" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="出生日期" prop="birth" :rules="[{ required: true, message: '出生日期是必填项' }]">
                        <el-date-picker v-model="formUser.birth" type="date" placeholder="请选择" clearable />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-form-item label="地址" prop="addr" :rules="[{ required: true, message: '地址是必填项' }]">
                    <el-input v-model="formUser.addr" placeholder="请输入地址" />
                </el-form-item>
            </el-row>
            <el-row style="justify-content: flex-end;">
                <el-form-item>
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="onSubmit">
                        确定
                    </el-button>
                </el-form-item>
            </el-row>
        </el-form>
        <!-- <template #footer>
            <div class="dialog-footer">

            </div>
        </template> -->
    </el-dialog>
</template>

<script setup>

import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
const { proxy } = getCurrentInstance()
//表格数据
let list = ref([])
// 表格标题
const tableLabel = reactive([
    {
        prop: 'name',
        label: '姓名'
    },
    {
        prop: 'age',
        label: '年龄'
    },
    {
        prop: 'sexLabel',
        label: '性别'
    },
    {
        prop: 'birth',
        label: '出生日期',
        width: 200
    },
    {
        prop: 'addr',
        label: '地址',
        width: 300
    },
])
// 分页数据
const config = reactive({
    name: '',
    total: 0,
    page: 1
})

// 搜索关键词
const formInline = reactive({
    keyword: ''
})
// 页码数变化时
const changePage = (page) => {
    console.log(page);
    config.page = page
    getUserData(config)
}
// 搜索
const handleSearch = () => {
    config.name = formInline.keyword
    getUserData(config)
}
// 控制对话框显示隐藏
const dialogVisible = ref(false)
const handleClose = (done) => {
    ElMessageBox.confirm('确定关闭吗?')
        .then(() => {
            proxy.$refs.userForm.resetFields()
            done()
        })
        .catch(() => {
            // catch error
        })
}
// 添加用户的form数据
const formUser = reactive({
    name: '',
    age: '',
    sex: '',
    birth: '',
    addr: ''
})

// 取消
const handleCancel = () => {
    dialogVisible.value = false
    proxy.$refs.userForm.resetFields()
}
//新增用户
const handleAdd = () => {
    action.value='add'
    dialogVisible.value = true
}
// 添加用户(确定按钮)
const onSubmit = () => {
    proxy.$refs.userForm.validate(async (valid) => {
        if (valid) {
            // 执行新增
            if (action.value == 'add') {
                let res = await proxy.$api.addUser(formUser)
                if (res) {
                    proxy.$refs.userForm.resetFields()
                    dialogVisible.value = false
                    getUserData(config)
                }
            } else {
                // 执行编辑
                formUser.sex == '男' ? (formUser.sex=0):(formUser.sex=1)
                let res = await proxy.$api.editUser(formUser)
                if(res){
                    dialogVisible.value=false
                    proxy.$refs.userForm.resetFields()
                    getUserData(config)
                }
            }
        } else {
            ElMessage({
                showClose: true,
                message: '请输入正确的内容',
                type: 'error'
            })
        }
    })
}
//编辑用户
const handleEdit = (row) => {
    console.log(row);
    action.value = 'edit'
    dialogVisible.value = true
    row.sex == 1? (row.sex='女') :(row.sex='男')
    // 浅拷贝
    Object.assign(formUser,row)
}
// 区分编辑和新增的状态
const action = ref('add')
// 删除用户
const handleDelete =(row)=>{
    ElMessageBox.confirm('你确定删除吗?')
    .then(async ()=>{
        await proxy.$api.deleteUser({
            id:row.id
        })
        ElMessage({
            showClose:true,
            message:'删除成功',
            type:'success'
        })
        getUserData(config)
    })
    .catch(()=>{
        
    })
}

// 获取列表数据
const getUserData = async (config) => {
    let res = await proxy.$api.getUserData(config)
    //总页数    
    config.total = res.count
    console.log(res);
    list.value = res.list.map((item) => {
        item.sexLabel = item.sex === 0 ? '男' : '女'
        return item
    })
}
onMounted(() => {
    // 获取列表数据
    getUserData(config)
})

</script>
<style lang="less">
.user-header {
    display: flex;
    justify-content: space-between;
    align-items: center
}

.sex-select {
    width: 200px;
}
</style>